<style>
/*树形菜单位置*/
.l1 {
  margin-left: 100px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 15px;
  padding-right: 40px;
}
/*表单位置*/
.l2 {
  margin-left: 130px;
}
/*树形菜单位置*/
.b1 {
  margin-top: 22px;
}

/*树形菜单的删除位置*/
.b3 {
  margin-left: 40px;
}
/*设置字体大小*/
.el-tree-node__label {
  font-size: 17px;
}
/*设置tree每行的高度*/
.el-tree-node__content {
  height: 38px;
}
</style>
<template>
  <div>
    <Breadcrumb>
      <BreadcrumbItem to="/main/myInfo">
        <e-icon icon-name="el-icon-s-home"></e-icon>主页
      </BreadcrumbItem>
      <BreadcrumbItem>
        <e-icon icon-name="fa fa-sitemap"></e-icon>职工管理
      </BreadcrumbItem>

      <BreadcrumbItem>部门管理
      </BreadcrumbItem>
    </Breadcrumb>
    <Divider />
    <Row>
      <Col class="l1" span="6">
        <Button type="primary" @click="addDept" icon="logo-buffer">
          添加部门
        </Button>
        <el-tree
          class="b1"
          :data="data"
          show-checkbox
          node-key="id"
          ref="tree"
          :props="defaultProps"
          :expand-on-click-node="false"
          :render-content="renderContent"
          @node-click="selectCheckDept"
        >
        </el-tree>

        <Button
          style="margin-top: 23px"
          type="error"
          ghost
          @click="getCheckedKeys"
          icon="ios-trash"
        >
          删除所选
        </Button>
      </Col>
      <Col class="l2" span="10">
        <Card style="width: 600px">
          <Form
            ref="DeptPo"
            :model="DeptPo"
            :rules="ruleValidate"
            :label-width="80"
          >
            <FormItem label="部门ID" prop="id">
              <Tooltip content="部门ID不可更改哦" placement="top"
                ><Input
                  style="width: 433px"
                  v-model="DeptPo.id"
                  disabled
                ></Input>
              </Tooltip>
            </FormItem>

            <FormItem label="父级部门" prop="parentId">
              <el-select
                v-model="DeptPo.parentId"
                clearable
                placeholder="请选择"
                @clear="handleClear"
                ref="selectUpResId"
                style="width: 433px"
              >
                <el-option
                  hidden
                  key="upResId"
                  :label="parentName"
                  v-model="DeptPo.parentId"
                >
                </el-option>
                <el-tree
                  :data="data2"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  :check-on-click-node="true"
                  @node-click="handleNodeClick"
                >
                </el-tree>
              </el-select>
            </FormItem>
            <FormItem label="部门代码" prop="code">
              <Input
                style="width: 433px"
                v-model="DeptPo.code"
                placeholder="请输入部门代码"
              ></Input>
            </FormItem>
            <FormItem label="部门名称" prop="name">
              <Input
                style="width: 433px"
                v-model="DeptPo.name"
                placeholder="请输入部门名称"
              ></Input>
            </FormItem>

            <FormItem label="排序码" prop="sortCode">
              <Input
                v-model="DeptPo.sortCode"
                style="width: 433px"
                placeholder="请输入部门排序码"
              ></Input>
            </FormItem>
            <FormItem>
              <Button
                icon="ios-jet"
                type="success"
                ghost
                @click="handleSubmit('DeptPo')"
                >保存</Button
              >
            </FormItem>
          </Form>
        </Card>
      </Col>
    </Row>
  </div>
</template>
<script>
export default {
  inject: ["reload"],
  data() {
    return {
      //下拉框显示的部门名
      parentName: "",
      //树形组件需要的数据对应
      defaultProps: {
        children: "children",
        label: "name",
      },
      //删除部门时的id，以及其子部门id
      deleteDeptId: [],
      //存放所有部门信息
      data: [],
      //修改部门时，选择树，不能有自己和子节点
      data2: [],
      //部门验证
      ruleValidate: {
        name: [
          {
            required: true,
            message: "部门名称不能为空",
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "部门代码不能为空",
            trigger: "blur",
          },
        ],
      },
      //点击左侧部门树，右侧表单存储该部门的信息
      DeptPo: {},
    };
  },
  created() {
    //页面加载时
    //查询部门
    this.selectDept();
  },

  methods: {
    //添加菜单，把右侧表单清空，并提示用户输入
    addDept() {
      this.$Message.info({
        duration: 2.5,
        background: true,
        content: "请在右侧表单输入部门信息",
      });
      this.DeptPo = {};
      this.parentName = "";
      this.data2 = this.data;
    },
    //点击删除按钮寻问是否删除，并保存id的list
    getCheckedKeys() {
      if (this.$refs.tree.getCheckedKeys().length > 0) {
        this.$Modal.confirm({
          title: "警告",
          content: "<p>你真的要删除这些部门么?</p>",
          onOk: () => {
            this.deleteCheckDept(this.$refs.tree.getCheckedKeys());
          },
          onCancel: () => {},
        });
      } else {
        this.$Message.warning({
          top: 30,
          duration: 2.5,
          background: true,
          content: "您未选择任何部门",
        });
      }
    },
    //删除选中部门
    deleteCheckDept(idList) {
      this.$axios
        .post("/dept/deleteCheckDept", idList)
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              duration: 2.5,
              background: true,
              content: "删除成功",
            });
            //删除成功，更新查询
            this.selectDept();
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除失败",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //删除单个部门
    deleteDept(id) {
      this.$axios
        .get("/dept/deleteDept", {
          params: {
            id: id,
          },
        })
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              duration: 2.5,
              background: true,
              content: "删除成功",
            });
            //删除成功，更新查询
            this.selectDept();
          } else if (result.data.code == -233) {
            this.$Message.error({
              duration: 2.5,
              background: true,
              content: result.data.msg,
            });
            //删除成功，更新查询
            this.selectDept();
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除失败",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //点击左侧部门时，获得部门树该节点的信息，通过信息查找部门详细信息，在右侧表单显示
    selectCheckDept(e) {
      this.selectDeptById(e.id);
    },
    //根据id查找菜单详细信息
    selectDeptById(id) {
      this.$axios
        .get("/dept/selectDeptById", {
          params: {
            id: id,
          },
        })
        .then((result) => {
          //查询出来的菜单信息赋值
          this.DeptPo = result.data.data;
          //判断有无父级菜单名称
          if (JSON.stringify(this.DeptPo.parentName) == "{}") {
          } else {
            this.parentName = this.DeptPo.parentName;
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.$axios
        .get("/dept/ListTreeData2", {
          params: {
            id: id,
          },
        })
        .then((result) => {
          this.data2 = result.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //渲染树形菜单的按钮和数据
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span class="b2">{node.label}</span>
          <span class="b3">
            <el-button
              size="mini"
              type="text"
              on-click={() => this.remove(node, data)}
            >
              删除
            </el-button>
          </span>
        </span>
      );
    },
    //树形菜单点击删除结点
    remove(node, data) {
      //若无子节点，则直接询问后删除
      if (node.childNodes.length == 0) {
        console.log(data);
        this.$Modal.confirm({
          title: "警告",
          content: "<p>该部门会被删除，您确定删除吗?</p>",
          onOk: () => {
            this.deleteDept(data.id);
          },
          onCancel: () => {},
        });
        //若有子节点，找出子节点后一起删除
      } else {
        this.deleteDeptId = [];
        this.deleteDeptId.push(data.id);
        node.childNodes.forEach((element) => {
          this.deleteDeptId.push(element.data.id);
          if (element.childNodes.length > 0) {
            element.childNodes.forEach((x) => {
              this.deleteDeptId.push(x.data.id);
              if (x.childNodes.length > 0) {
                x.childNodes.forEach((y) => {
                  this.deleteDeptId.push(y.data.id);
                  if (y.childNodes.length > 0) {
                    y.childNodes.forEach((z) => {
                      this.deleteDeptId.push(z.data.id);
                    });
                  }
                });
              }
            });
          }
        });
        this.$Modal.confirm({
          title: "警告",
          content: "<p>该部门和子部门都会被删除，您确定删除吗?</p>",
          onOk: () => {
            this.deleteCheckDept(this.deleteDeptId);
          },
          onCancel: () => {},
        });
      }
    },
    //点击保存菜单时，可能添加可能修改
    handleSubmit(name) {
      console.log(this.DeptPo.parentId);
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$axios
            .post("/dept/updateDept", this.DeptPo)
            .then((result) => {
              if (result.data.code == 0) {
                this.$Message.success({
                  duration: 2.5,
                  background: true,
                  content: result.data.data,
                });
                //修改数据成功，更新树
                this.selectDept();
              } else {
                this.$Message.error({
                  duration: 2.5,
                  background: true,
                  content: "操作失败",
                });
              }
              console.log(result.data);
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
        }
      });
    },
    //查询菜单
    selectDept() {
      this.$axios
        .get("/dept/ListTreeData")
        .then((result) => {
          //赋值给菜单信息
          this.data = result.data.data;
          this.data2 = this.data;
        })
        .catch((err) => {});
    },
    //下拉框选中菜单时
    handleNodeClick(data) {
      this.parentName = data.name;
      this.DeptPo.parentId = data.id;
      this.$refs.selectUpResId.blur();
    },
    //点击清空下拉框按钮时触发
    handleClear() {
      this.parentName = "";
      this.DeptPo.parentId = null;
    },
  },
};
</script>